package com.joven.shelltest.utils.redisdelay;

import com.alibaba.fastjson.JSONObject;
import com.joven.shelltest.utils.RedisUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author wzj
 * @Date 2023-07-26 10:01
 **/
@Component
public class RedisDelayListWrapper implements ApplicationContextAware {

    private final Set<String> topic = new CopyOnWriteArraySet<>();

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private  ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    }

    public void publish(String key, Object val, long delayTime) {
        topic.add(key);
        String strVal = val instanceof String ? (String) val : JSONObject.toJSONString(val);
        redisUtils.zAdd(key, strVal, System.currentTimeMillis() + delayTime);
    }

//    @Scheduled(fixedRate = 10_000)
    public void schedule() {
//        for (String specialTopic : topic) {
//            String cell = redisUtils.fetchOne(specialTopic);
//            if (cell != null) {
//                applicationContext.publishEvent(new DelayMsg(this, cell, specialTopic));
//            }
//        }
    }
}
